import { createRouter, createWebHistory } from 'vue-router'
import Home from '../view/Home.vue'
import About from '../view/About.vue'
// 新增后台管理系统相关页面
import Login from '../view/Login.vue'
import Dashboard from '../view/Dashboard.vue'
import UserList from '../view/UserList.vue'
import Statistics from '../view/Statistics.vue'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  // 后台管理系统路由
  { path: '/login', component: Login },
  {
    path: '/admin', // 后台主路由，避免和首页冲突
    component: Dashboard,
    children: [
      { path: 'users', component: UserList },
      { path: 'statistics', component: Statistics },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：实现简单权限控制
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  // 只对后台管理系统相关页面做校验
  if (to.path.startsWith('/admin')) {
    if (!token) {
      next('/login')
    } else {
      next()
    }
  } else if (to.path === '/login' && token) {
    next('/admin/users')
  } else {
    next()
  }
})

export default router
